<template>
  <el-upload
    class="avatar-uploader"
    action=""
    :http-request="upload"
    :show-file-list="false"

    :before-upload="beforeAvatarUpload"
  >
    <img v-if="url" :src="url" class="avatar">
    <i v-else class="el-icon-plus avatar-uploader-icon" />
  </el-upload>
</template>

<script>
import COS from 'cos-js-sdk-v5'
export default {
  name: 'Upload',
  props: {
    url: {
      type: String,
      default: ''
    }
  },
  data() {
    return {

    }
  },
  created() {
    this.cos = new COS({
      SecretId: 'AKIDiEVWIp8D1YopgGfqlPlqeGemeFZcOuAA',
      SecretKey: 'kEQLyLTKvHNCk11kCNIvHMAhxxg9LFsE'
    })
  },

  methods: {
    upload({ file }) {
      this.cos.putObject({
        Bucket: 'liuyear-1307897820', /* 必须 */
        Region: 'ap-shanghai', /* 存储桶所在地域，必须字段 */
        Key: file.name, /* 必须 */
        StorageClass: 'STANDARD',
        Body: file // 上传文件对象

      }, (err, data) => {
        if (err) {
          console.log(err)
        }

        this.$emit('updataimg', data.Location)
      })
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    }
  }
}
</script>

<style lang="scss" scoped>
.avatar-uploader {
  ::v-deep {
    .el-upload {
      border: 1px dashed #d9d9d9;
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
    }
    .el-upload:hover {
      border-color: #409EFF;
    }
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
}
</style>
